<template>
    <div class="dashboard-container">

      <!-- 顶部操作栏 -->
      <div class="search">
        <el-form :inline="true" class="left">
          <el-form-item>
            <el-button type="primary" @click="handleAdd('create')">
              <i class="el-icon-plus"></i>
              新增
            </el-button>
          </el-form-item>
        </el-form>
        <el-form :inline="true" :model="params" class="right">
          <el-form-item>
            <el-select v-model="params.userId" style="width: 100%;" filterable clearable placeholder="请选择用户">
              <el-option v-for="item in userList" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select v-model="params.patternId" style="width: 100%;" filterable clearable placeholder="请选择证书类型">
              <el-option v-for="item in certificateTypeList" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" plain @click="handleSearch">
              查询
              <i class="el-icon-search"></i>
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 内容栏 -->
      <div class="body">

        <!-- 列表 -->
        <el-table :data="list" v-loading="loading">
          <el-table-column label="姓名" prop="realName"></el-table-column>
          <el-table-column label="证书名称" prop="patternName"></el-table-column>
          <el-table-column label="证书编码" prop="code"></el-table-column>
          <el-table-column label="过期时间" prop="expireTime"></el-table-column>
          <el-table-column label="状态">
            <tempale slot-scope="{row}">
              <el-tag type="success" v-if="row.status=='正常'">{{ row.status }}</el-tag> 
              <el-tag type="warning" v-if="row.status=='预警'">{{ row.status }}</el-tag> 
              <el-tag type="danger" v-if="row.status=='过期'">{{ row.status }}</el-tag> 
            </tempale>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="{row}">
              <el-button type="text" @click="handleAdd('update', row)">
                <i class="el-icon-edit-outline"></i>
                编辑
              </el-button>
              <el-button type="text danger" @click="handleDelete(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="page">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="params.pageIndex+1"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="params.pageCount"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </div>

      </div>

      <!-- 新增、编辑 -->
      <el-dialog 
        :visible.sync="dialogVisible" 
        :close-on-click-modal="false"
        @close="dialogVisible=false"
        :title="dialogType=='create'?'创建资质':'编辑资质'"
        width="600px"
      >
        <el-form ref="form" :rules="rules" :model="temp" label-width="100px">
          <el-form-item label="用户" prop="userId">
            <el-select v-model="temp.userId" style="width: 100%;" filterable clearable placeholder="请选择用户">
              <el-option v-for="item in userList" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item label="证书类型" prop="patternId">
            <el-select v-model="temp.patternId" style="width: 100%;" filterable clearable placeholder="请选择证书类型">
              <el-option v-for="item in certificateTypeList" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="资质编码" prop="code">
            <el-input placeholder="请输入资质编码" v-model="temp.code"></el-input>
          </el-form-item>
          <el-form-item label="过期时间" prop="expireTime">
            <el-date-picker
              v-model="temp.expireTime"
              type="date"
              placeholder="选择日期"
              style="width: 100%;"
              value-format="timestamp"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submit('form')">提交</el-button>
            <el-button @click="dialogVisible = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>

    </div>
</template>
  
<script>
import { mapGetters } from 'vuex'
import { certificateCreate, certificateUpdate, certificateGetList, certificateDelete } from '@/api/certificate'
import { patternGetList } from '@/api/pattern';
import { userGetList } from '@/api/user';
import moment from 'moment'
import { transfromData } from '@/utils/tools';
  
export default {
    name: 'StaffCertificate',
    computed: {
      ...mapGetters([
        'name'
      ])
    },
    data(){
      return {
        rules: {
          patternId: [{ required: true, message: '请选择资质', trigger: 'blur' }],
          userId: [{ required: true, message: '请选择用户', trigger: 'blur' }],
          expireTime: [{ required: true, message: '请填写过期时间', trigger: 'blur' }],
          code: [{ required: true, message: '请填写证书编号', trigger: 'blur' }],
        },
        params: {
          companyId: 1,
          pageCount: 10,
          pageIndex: 0,
          name: '',
        },
        total: 0,
        list: [],
        dialogVisible: false,
        dialogType: 'create',
        temp: {
          code: '',
          expireTime: '', //过期时间
          files: [], //文件列表
          userId: '',
          patternId: ''
        },
        loading: false,
        certificateTypeList: [],
        userList:[] 
      }
    },
    async mounted(){
      // 获取证书信息
      let data = await patternGetList({ type: 0, pageCount: 9999 })
      this.certificateTypeList = data.list.map(item=>{
        return { label: item.name, value: item.id }
      })
      // 获取用户列表
      let UserData = await userGetList({type: 1, companyId: 1, pageCount: 9999})
        this.userList = UserData.list.map(item=>{
          return { label: item.realName, value: item.id }
      })
      this.handleSearch();
    },
  
    methods:{
      
      // 点击删除
      handleDelete(id){
        this.$confirm('此操作将永久删除该资质, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          await certificateDelete({ id })
          this.getData();
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      },
      //提交表单
      submit(formName){
        this.$refs[formName].validate(async (valid) => {
          if (valid) {
            if(this.dialogType =='create'){
              await certificateCreate(this.temp)
              this.$message.success('创建成功')
            }else{
              await certificateUpdate(this.temp)
              this.$message.success('修改成功')
            }
            this.handleSearch();
            this.dialogVisible = false;
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      // 点击新增、编辑
      handleAdd(type, row){
        this.dialogType = type;
        this.dialogVisible = true;
        if(type=='create'){
          this.temp = {
            code: '',
            expireTime: '', //过期时间
            files: [], //文件列表
            userId: '',
            patternId: ''
          }
        }else{
          let temp = JSON.parse(JSON.stringify(row));
          temp.expireTime = moment(temp.expireTime).valueOf();
          this.temp = temp;
        }
      },
      //修改搜索条件
      handleSearch(){
        this.params.pageIndex = 0;
        this.getData();
      },
      //加载列表数据
      async getData(){
        this.loading = true
        let data = await certificateGetList(this.params)
        this.loading = false;
        this.total = data.totalCount;
        this.list = data.list.map(item=>{
          item.expireTime = moment(item.expireTime).format('YYYY-MM-DD')
          item.patternName = transfromData(this.certificateTypeList, item.patternId)
          item.realName = transfromData(this.userList, item.userId)
          // 判断一下过期时间， 1. 正常 2. 临近1个月到期的 3. 过期
          let nowDate = moment().valueOf();
          let expireDate = moment(item.expireTime).valueOf();
          let tipDate = moment(item.expireTime).subtract(1, 'months').valueOf();
          if(nowDate>expireDate){
            item.status = '过期'
            item.tip = false;
          }else if(nowDate<tipDate){
            item.status = '正常'
            item.tip = true;
          }else if(nowDate>=tipDate){
            item.status = '预警'
            item.tip = true
          }
          return item;
        });
      },
      // 修改每页数量
      handleSizeChange(val){
        this.params.pageIndex = 0;
        this.params.pageCount = val;
        this.getData();
      },
      // 切换分页
      handleCurrentChange(val){
        this.params.pageIndex = val - 1;
        this.getData();
      }
    }
}
</script>
  
<style lang="scss" scoped>
.dashboard {
    &-container {
      margin: 30px;
      position: relative;
      .right{
        position: absolute;
        right: 0;
        top: 0;
      }

      .page{
        padding: 20px 0;
        text-align: center;
      }
    }
    &-text {
      font-size: 30px;
      line-height: 46px;
    }
}
</style>
  